package cn.ratel.route;

import cn.ratel.component.Handlers;
import cn.ratel.component.Plugins;
import cn.ratel.component.Routes;
import cn.ratel.ioc.IocKit;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RatelFilter implements Filter {
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Routes.init(filterConfig.getServletContext());
		IocKit.init();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String uri = req.getRequestURI();
		if (!uri.contains(".")) {
			try {
				Handlers.me().getHandlers().get(0).handle(new HandlerContext(req, res, uri));
			} catch (Exception e) {
				ExceptionHolder.getHolder().hold(req, res, e);
			}
		}
		if (!res.isCommitted()) {
			chain.doFilter(req, res);
		}
	}

	@Override
	public void destroy() {
		Plugins.me().getPlugins().forEach(Plugins.Plugin::stop);
		IocKit.destroy();
	}
}
